<template>
    <el-dialog
      class="ba-operate-dialog"
      :close-on-click-modal="false"
      :model-value="baTable.form.operate ? true : false"
      @close="baTable.toggleForm"
    >
      <template #header>
        <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']">
          {{ baTable.form.operate !== "edit" ? "添加" : "编辑" }}
        </div>
      </template>
      <el-scrollbar
        v-loading="baTable.form.loading"
        class="ba-table-form-scrollbar"
      >
        <div
          class="ba-operate-form"
          :class="'ba-' + baTable.form.operate + '-form'"
          :style="'width: calc(100% - ' + baTable.form.labelWidth! / 2 + 'px)'"
        >
          <el-form
            ref="formRef"
            @keyup.enter="baTable.onSubmit(formRef)"
            :model="baTable.form.items"
            label-position="right"
            :label-width="baTable.form.labelWidth + 'px'"
            :rules="rules"
            v-if="!baTable.form.loading"
          >
            <el-form-item label="工序号" prop="process">
              <el-input
                v-model="baTable.form.items!.process"
                placeholder="请输入工序号"
              />
            </el-form-item>
            <el-form-item prop="processName" label="工序名称">
              <el-input
                v-model="baTable.form.items!.processName"
                type="string"
                placeholder="请输入工序名称"
              ></el-input>
            </el-form-item>
            <FormItem
              label="工序类型"
              v-model="baTable.form.items!.type"
              type="radio"
              prop="type"
              :data="{
                content: { 0: '人工', 1: '机加工' },
                childrenAttr: { border: true },
              }"
            />
            <el-form-item prop="prepareTime" label="准备时间(分钟)">
              <el-input
                v-model="baTable.form.items!.prepareTime"
                type="string"
                placeholder="请输入单件额定准备时间"
              ></el-input>
              <div class="block-help">单件额定准备时间</div>
            </el-form-item>
            <el-form-item prop="productTime" label="加工时间(分钟)">
              <el-input
                v-model="baTable.form.items!.productTime"
                type="string"
                placeholder="请输入单件额定加工时间"
              ></el-input>
              <div class="block-help">单件额定加工时间</div>
            </el-form-item>
            <el-form-item prop="afterTime" label="结束时间(分钟)">
              <el-input
                v-model="baTable.form.items!.afterTime"
                type="string"
                placeholder="请输入单件额定结束工时间"
              ></el-input>
              <div class="block-help">单件额定结束时</div>
            </el-form-item>
            <el-form-item label="作业指导书">
              <el-upload
                ref="uploadPdfRef"
                :limit="1"
                accept=".doc,.docx,.xlsx,.pdf,.jpg,.png,.jpeg"
                class="upload-demo"
                :action="state.instructions"
                :auto-upload="false"
                :on-change="changUploadPdf"
                :on-remove="handleRemovePdf"
                :http-request="handleUplodFilePdf"
              >
                <el-button type="primary">上传本地文件</el-button>
                <template #tip>
                  <div class="el-upload__tip">
                    支持doc、docx、xlsx、pdf 、jpg等常见文件格式，大小不超过5MB
                  </div>
                </template>
              </el-upload>
              <el-link
                @click="equipSpecifications(baTable.form.items!.information)"
                type="primary"
                :underline="false"
                style="font-size: 12px; vertical-align: baseline"
                >{{ baTable.form.items!.informationname }}</el-link
              >
            </el-form-item>
          </el-form>
        </div>
      </el-scrollbar>
      <template #footer>
        <div
          :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'"
        >
          <el-button @click="baTable.toggleForm('')">取消</el-button>
          <el-button
            v-blur
            :loading="baTable.form.submitLoading"
            @click="baTable.onSubmit(formRef)"
            type="primary"
          >
            {{ baTable.form.operate === "itemAdd" ? "确定并新增下一项" : "确定" }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </template>
  <script lang="ts" setup>
  import { reactive, ref, inject, onMounted } from "vue";
  import type baTableClass from "@/utils/baTable";
  import { ElNotification } from "element-plus"; //处理导航信息
  import type {
    ElForm,
    FormItemRule,
    FormRules,
    UploadUserFile,
    UploadProps,
    UploadFiles,
    UploadFile,
    UploadRequestOptions,
    UploadInstance,
  } from "element-plus";
  import FormItem from "@/components/formItem/index.vue";
  import { _download, _upload } from "@/utils/axios";
  
  const formRef = ref<InstanceType<typeof ElForm>>();
  const baTable = inject("baTable") as baTableClass;
  const station = inject("station") as any;
  const equipUnit = inject("equipUnit") as any;
  const bom = inject("bom") as any;
  
  const uploadPdfRef = ref<UploadInstance>();
  //说明书pdf
  const pdfFileList = ref<UploadUserFile[]>([]);
  const pdfRealUploadFile = ref<UploadUserFile[]>([]);
  
  const state: {
    typeOptions: any;
    stationOptions: any;
    instructions: string;
    host: string;
    form: anyObj;
  } = reactive({
    typeOptions: [], //物料类型列表
    stationOptions: [], //工作中心列表
    instructions: "", //说明书 作业指导书
    host: "",
    form: {},
  });
  
  const defaultProps = {
    children: "children",
    label: "name",
  };
  
  // 关键词过滤
  const filterNode = (value: string, data: any) => {
    if (!value) return true;
    return data.name.includes(value);
  };
  const handleCheckChange = (row: any, node: any) => {
    console.log("row", row, "node", node);
    if (node.checkedKeys.length == 0) {
      baTable.form.items!.workshopCode = "";
      baTable.form.items!.workshopName = "";
    } else {
      baTable.form.items!.workshopCode = row.code;
      baTable.form.items!.workshopName = row.name;
    }
  };
  
  const rules = reactive<FormRules>({
    process: [{ required: true, message: "工序号不能为空", trigger: "blur" }],
    type: [{ required: true, message: "工序类型不能为空", trigger: "blur" }],
    processName: [
      { required: true, message: "工序名称不能为空", trigger: "blur" },
    ],
    prepareTime: [
      { required: true, message: "准备时间不能为空", trigger: "blur" },
    ],
    productTime: [
      { required: true, message: "加工时间不能为空", trigger: "blur" },
    ],
  });
  
  //移除说明书pdf
  const handleRemovePdf: UploadProps["onRemove"] = (
    uploadFile: UploadFile,
    uploadFiles: UploadFiles
  ) => {
    console.log(uploadFile, uploadFiles);
    const { uid } = uploadFile;
    const selectFileList = pdfFileList.value.filter((item) => {
      return item.uid != uid;
    });
    pdfFileList.value = selectFileList;
  };
  
  //设备说明书pdf文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
  const changUploadPdf: UploadProps["onChange"] = (
    uploadFile: UploadFile,
    uploadFiles: UploadFiles
  ) => {
    console.log("文件限制", uploadFile, uploadFiles);
    const { uid, name, size } = uploadFile;
    //   文件类型限制
    const fileTypeFlag = /^.doc|.docx|.xlsx|.pdf|.jpg|.jpeg|.png$/.test(
      name.substring(name.lastIndexOf(".")).toLowerCase()
    );
    if (!fileTypeFlag) {
      ElNotification({
        type: "warning",
        message: "文件类型只能是.doc|.docx|.xlsx|.pdf|.jpg|.jpeg|.png",
      });
      const selectFileList = pdfFileList.value.filter((item) => {
        return item.uid != uid;
      });
      pdfFileList.value = selectFileList;
      return;
    }
    //文件大小进行校验
    if ((size as number) > 1024 * 1024 * 5) {
      ElNotification({
        type: "warning",
        message: "文件大小不能超过5Mb",
      });
      const selectFileList = pdfFileList.value.filter((item) => {
        return item.uid != uid;
      });
      pdfFileList.value = selectFileList;
      return;
    }
    // 将上传PDF说明书文件信息存入列表
    pdfFileList.value.push(uploadFile);
    pdfRealUploadFile.value = [];
    let formData = new FormData();
    formData.append("file", uploadFiles[0].raw as any); //添加文件对象
    formData.append("name", "pdf"); //添加文件对象
    _upload("/common/upload", formData, "").then((res: any) => {
      // baTable.form.items!.information = res.data.url;
      baTable.form.items!.information =
        state.host === "" ? res.data.url : state.host + res.data.fileName;
      baTable.form.items!.informationname = res.data.originalFilename;
    });
  };
  //允许自行实现上传文件的请求 再用户触发了realSubmit后触发
  const handleUplodFilePdf = (options: UploadRequestOptions) => {
    console.log("允许自行实现上传文件的请求", options);
    pdfRealUploadFile.value.push(options.file);
    let formData = new FormData();
    formData.append("file", options.file); //添加文件对象
    formData.append("name", "pdf"); //添加文件对象
    _upload("/common/upload", formData, "").then((res: any) => {
      state.form.information = res.data.url;
      //再上传cep图片
      // uploaCepfRef.value!.submit();
    });
  };
  
  //打开文件
  const equipSpecifications = (url: any) => {
    window.open(url);
  };
  
  onMounted(() => {
    //获取工作中心数据
    station.getStationByRole().then((res: any) => {
      state.stationOptions = res;
      console.log("stationOptions", res);
    });
    //   baTable.form.items!.id = equipUnit.stationInfo.id;
    baTable.form.items!.materialCode = bom.bomInfo.code;
    baTable.form.items!.name = bom.bomInfo.name;
    baTable.form.items!.workshopCode = bom.bomInfo.workshopCode;
    baTable.form.items!.workshopName = bom.bomInfo.workshopName;
  });
  </script>
  <style lang="scss" scoped>
  .el-scrollbar {
    overflow: auto;
    position: relative;
    height: 100%;
  
    .el-scrollbar__wrap {
      overflow: auto;
      height: 100%;
    }
  }
  .tree-border {
    width: 100%;
    margin-top: 5px;
    border: 1px solid #e5e6e7;
    // background: #fff none;
    border-radius: 4px;
  }
  </style>
  